package cn.zl.common.file;

import cn.zl.ZLMediaServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

public class H264File {

    private static final Logger logger = LoggerFactory.getLogger(H264File.class);

    /**
     * 每次读取大小
     */
    private static final int BUF_SIZE = 64 * 1024;

    private String path;

    public H264File(String path) {
        this.path = path;
    }

    public void read() {
        try {
            File file = new File(path);
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream in = new BufferedInputStream(fis)) {

                byte[] buffer = new byte[BUF_SIZE]; // 从文件读的字节存入的地方
                byte[] nalu = null;            // 临时存储一个 nalu 单元内容
                byte[] firstHalfNalu = null;   // 跨buffer nalu前半段
                byte[] secondHalfNalu = null;			// 跨buffer nalu后半段
                int len = 0; // 每次从文件读的字节数
                int state = 0;							//状态机，值范围：0、1、2、3
                boolean first = true; // 是否是第一个起始码
                boolean cross = false;	// nalu 是否跨buffer

                while (-1 != (len = in.read(buffer, 0, BUF_SIZE))) {
                    logger.info("read len {}", len);
                    int start = 0; //第一个nalu的起始位置
                    int offset = 0; // 当前循环中的偏移量
                    if (first && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0x00 && buffer[3] == 0x01) {
                        first = false;
                        offset += 4;
                    } else {
                        logger.error("read H264 File header error");
                        break;
                    }
                    while (offset <= len-4) {
                        if (buffer[offset] == 0x00 && buffer[offset + 1] == 0x00 && buffer[offset + 2] == 0x00 && buffer[offset + 3] == 0x01) {
                            if(cross){

                            } else {
                                    int naluSize = offset - start;
                                    nalu = new byte[naluSize];
                                    System.arraycopy(buffer, start, nalu, 0, naluSize);
                            }
                            logger.info("offset {}", offset);
                            offset += 4;
                            start = offset; // 当前位置变成新的起始位置
                        } else {
                            offset ++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


}
